<template>
    <el-container ref="ref__container">
        <el-aside ref="ref__aside" width="auto" class="t-aside">
            <el-header class="logo">
                <transition name="el-fade-in-linear">
                    <span v-if="!isCollapse">{{$t('message.term.system_name')}}</span>
                </transition>
            </el-header>
            <div class="el-scrollbar" :style="scrollbarStyle">
                <el-menu ref="ref__siderMenu" :class="{'el-menu-vertical':!isCollapse}"
                         :default-active="siderMenuCurrentIndex"
                         @open="handleOpen" @close="handleClose"
                         :collapse="isCollapse" background-color="#515a6e"
                         text-color="hsla(0,0%,100%,.7)"
                         active-text-color="#2d8cf0"
                         :router="true">
                    <!-- 这里增加菜单 -->
                    <el-menu-item index="court-address">
                        <i class="el-icon-menu"></i>
                        <span slot="title">{{$t('message.term.court_address')}}</span>
                    </el-menu-item>
                    <el-menu-item index='widget'>
                        <i class="el-icon-menu"></i>
                        <span slot="title">{{$t('message.term.widget')}}</span>
                    </el-menu-item>



                </el-menu>
                <div class="el-scrollbar__bar is-vertical">
                    <div class="el-scrollbar__thumb" :style="scrollbarThumbStyle"></div>
                </div>
            </div>
        </el-aside>


        <el-container>
            <el-header class="banner">
                <div style="float: left">
                    <i :class="iconFoldState" @click="collapsedSider"></i>
                </div>

                <el-dropdown>
                    <i class="el-icon-setting" style="margin-right: 15px;"></i>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click.native="handleLogout">{{$t('message.term.logout')}}</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
                <span></span>
            </el-header>
            <!-- tabs路由 -->
            <TabsRouter></TabsRouter>
            <el-main>
                <el-breadcrumb separator-class="el-icon-arrow-right">
                    <el-breadcrumb-item :to="path(index)" v-for="(item, index) in $route.matched" :key="index">
                        {{$t(item.meta.title)}}
                    </el-breadcrumb-item>
                </el-breadcrumb>
                <!-- 子页面内容 -->
                <router-view/>
                <div class="copyright">{{$t('message.term.copyright')}}</div>
            </el-main>
        </el-container>
    </el-container>


</template>

<script>
    import {API} from '@/customized/http/api';
    import TabsRouter from '@/components/TabsRouter.vue';
    export default {
        name: 'Home',
        components: {
            TabsRouter
        },
        data() {
            return {
                screenHeight: 0,
                isCollapse: false,
                scrollBlockPercentHeight: 0,
                scrollBlockPercentPosition: 0,
                logoHeight: 56,
                stepLength: 10, //滚动条步长,单位是px
                isScrollDrag: false,
                scrollDragStart: 0,
                siderMenuCurrentIndex: "1"
            };
        },
        created: function () {
            /* 内容页面的高度计算 */
            this.screenHeight = window.innerHeight;
        },
        mounted() {
            window.onresize = () => { /* 内容页面的高度计算 */
                return (() => {
                    this.screenHeight = window.innerHeight;
                })()
            }

            this.$nextTick(() => {
                /** 设置鼠标滚轮事件，为侧边栏滚动做准备 */
                if (window.addEventListener) {//FF,火狐浏览器会识别该方法
                    window.addEventListener('DOMMouseScroll', this.wheel, true);
                }
                window.onmousewheel = document.onmousewheel = this.wheel;//W3C

                //鼠标按下事件
                let scrollbarThumb = document.getElementsByClassName("el-scrollbar__thumb")[0];
                scrollbarThumb.onmousedown = (event) => {
                    this.isScrollDrag = true;
                    this.scrollDragStart = event.clientY;
                };

                //鼠标移动
                window.onmousemove = (e) => {
                    if (this.isScrollDrag == false) {
                        return;
                    }
                    //获取y
                    let nowClientY = e.clientY;
                    //计算移动后的顶部的偏移量
                    let speed = nowClientY - this.scrollDragStart;
                    this.scrollDragStart = nowClientY;//每次更新scrollDragStart，那么新位置减去旧位置就能得到速度
                    this.handle(parseFloat(speed * -1) / this.stepLength);
                }

                //鼠标抬起事件
                window.onmouseup = () => {
                    //开关关闭
                    this.isScrollDrag = false;
                    this.scrollDragStart = 0;
                }
            });

            /**
             * 根据当前页面访问路径高亮菜单对应的选项
             */
            this.focusSiderMenuIndex();
        },
        destroyed() {
            window.removeEventListener('DOMMouseScroll', this.wheel, true);
        },
        watch: {
            // 如果 `clientHeight` 发生改变，这个函数就会运行
            screenHeight: function () { /* 内容页面的高度计算 */
                this.changeFixed(this.screenHeight)
            },
            /** 监听computed.account */
            account: function (oldVal, newVal) {
                console.log("$store.getters.account => " + newVal);
            },
            '$route.path': function (newVal, oldVal) {
                /**
                 * 根据当前页面访问路径高亮菜单对应的选项
                 */
                this.focusSiderMenuIndex();
            }
        },
        computed: {
            /** 要监听vuex中的帐户信息，必需配置computed */
            account() {
                return this.$store.state.account;
            },
            /** 显示当前请求页面的路径，供面包屑使用 */
            path() {
                return function (index) {
                    return this.$route.matched[index];
                }
            },
            /** 左侧菜单的实际高度 */
            scrollbarStyle() {
                return {
                    height: (this.screenHeight - this.logoHeight) + "px"
                }
            },
            /** 左侧菜单滚动条的实际高度和在滚动栏中的相对位置 */
            scrollbarThumbStyle() {
                return {
                    height: this.scrollBlockPercentHeight + "%",
                    transform: "translateY(" + this.scrollBlockPercentPosition + "%)",
                }
            },
            /** 左侧菜单折叠与展开显示不同的图标 */
            iconFoldState() {
                return this.isCollapse ? "el-icon-s-unfold" : "el-icon-s-fold";
            }
        },
        methods: {
            /** 右侧内容区需要填满可视窗口，ref__container包含了banner */
            changeFixed(screenHeight) {
                /* 内容页面的高度计算 */
                this.$refs.ref__container.$el.style.height = screenHeight + "px";
            },
            /** 左侧菜单伸缩开关 */
            collapsedSider() {
                this.isCollapse = !this.isCollapse;
            },
            /** 弹出注销对话框 */
            handleLogout() {
                this.$confirm(this.$t('message.notice.confirm_logout'), this.$t('message.notice.tips'), {
                    confirmButtonText: this.$t('message.term.confirm'),
                    cancelButtonText: this.$t('message.term.cancel'),
                    type: 'warning'
                }).then(() => {
                    this.logout();
                }).catch(() => {
                });
            },
            /** 注销 */
            logout() {
                /** 全局加载中开启 */
                const loading = this.$loading({
                    lock: true
                });

                API.logout({}).then(() => {
                    /** 全局加载中关闭 */
                    loading.close();
                    this.$router.push('/login').catch(err => {
                        err
                    });
                }).catch(() => {
                });
            },
            handleOpen(key, keyPath) {
                console.log(key, keyPath);
            },
            handleClose(key, keyPath) {
                console.log(key, keyPath);
            },
            /** 鼠标滚轮事件 */
            wheel(e) {
                let isScrollbarTarget = e.path.some((item) => {
                    /**
                     * e.path能返回触发当前事件的元素的层次关系，
                     * 如果其中有一个是el-scrollbar，则说明当前鼠标在侧边栏处滚动了滚轮
                     * */
                    return item.className == "el-scrollbar";
                });

                if (!isScrollbarTarget) {
                    /**
                     * 如果鼠标不是在侧边栏处滚动滚轮，则不会触发菜单栏的滚动逻辑
                     */
                    return;
                }

                let delta = 0;
                if (!e) e = window.event;
                if (e.wheelDelta) {//IE、chrome浏览器使用的是wheelDelta，并且值为“正负120”
                    delta = e.wheelDelta / 120;
                    if (window.opera) delta = -delta;//因为IE、chrome等向下滚动是负值，FF是正值，为了处理一致性，在此取反处理
                } else if (e.detail) {//FF浏览器使用的是detail,其值为“正负3”
                    delta = -e.detail / 3;
                }
                if (delta)
                    this.handle(delta);
            },
            /** 处理鼠标滚轮逻辑 */
            handle(delta) {
                //console.log("delta => " + delta);
                let siderMenu = this.$refs.ref__siderMenu.$el;
                let scrollbarThumb = document.getElementsByClassName("el-scrollbar__thumb")[0];

                let siderMenuHeight = siderMenu.clientHeight;//左侧菜单的高度
                let scrollBarHeight = this.screenHeight - this.logoHeight;//滚动栏高度
                let siderMenuHiddenHeight = siderMenuHeight - scrollBarHeight; // 边栏被隐藏的长度

                if (!this.isScrollBarShow(scrollBarHeight, siderMenuHeight)) {
                    /** 如果窗口高度减去logo区域高度的值大于菜单的长度，则需要隐藏滚动条*/
                    return;
                }

                /** 边栏偏移速度步长应该和滚动条移动步长保持一致
                 *  那么有如下计算公式：
                 *  设x为滚动条滑块高度
                 *  设y为滚动次数
                 *  设10为步长
                 *
                 *  x + 10 * y = scrollBarHeight
                 *  10 * y = siderMenuHeight - scrollBarHeight
                 *  x = 2 * scrollBarHeight - siderMenuHeight
                 * */
                this.scrollBlockPercentHeight = (2 * scrollBarHeight - siderMenuHeight) * 100 / scrollBarHeight;

                let marginTopComputable = siderMenu.style.marginTop ? this.getComputedCssValue(siderMenu.style.marginTop) : 0;
                let newMarginTopComputable = marginTopComputable + delta * this.stepLength;

                if (newMarginTopComputable * -1 > siderMenuHiddenHeight) {
                    /** 如果向上偏移距离大于边栏被隐藏的长度，说明滚动已经到底了 */
                    siderMenu.style.marginTop = siderMenuHiddenHeight * -1 + "px";
                    let offsetRatio = this.computeOffsetRatio(siderMenuHiddenHeight * -1, scrollBarHeight);
                    //console.log("offsetRatio => " + offsetRatio);
                    scrollbarThumb.style.transform = "translateY(" + offsetRatio + "%)";
                    return;
                } else if (newMarginTopComputable > 0) {
                    /** 如果向下偏移距离大于0，说明滚动已经到顶了 */
                    siderMenu.style.marginTop = 0 + "px";
                    let offsetRatio = this.computeOffsetRatio(0, scrollBarHeight);
                    scrollbarThumb.style.transform = "translateY(" + offsetRatio + "%)";
                    return;
                }

                siderMenu.style.marginTop = newMarginTopComputable + "px";

                let offsetRatio = this.computeOffsetRatio(newMarginTopComputable, scrollBarHeight);
                scrollbarThumb.style.transform = "translateY(" + offsetRatio + "%)";
            },
            /** 判断是否需要显示滚动条 */
            isScrollBarShow(scrollBarHeight, siderMenuHeight) {
                if (scrollBarHeight >= siderMenuHeight) {
                    /**
                     * 当浏览器伸缩大小时需要此段逻辑
                     * 当浏览器窗口很小时，把滚动条拉到最下面，此时侧边栏到底
                     * 扩大浏览器窗口，新窗口大小能容纳整个侧边栏，此时应该把侧边栏的marginTop设置为0
                     * 让整个目录显示出来
                     * */
                    let siderMenu = this.$refs.ref__siderMenu.$el;
                    /* 得到当前侧边栏偏移位置 */
                    let marginTopComputable = siderMenu.style.marginTop ? this.getComputedCssValue(siderMenu.style.marginTop) : 0;
                    if (marginTopComputable < 0) {
                        /* 如果已经发生滚动，需要把偏移取消掉 */
                        siderMenu.style.marginTop = 0 + "px";
                    }

                    /** 如果窗口高度减去logo区域高度的值大于菜单的长度，则需要隐藏滚动条*/
                    this.scrollBlockPercentHeight = 0; /* 滚动条滑块设置高度为0 */
                    this.scrollBlockPercentPosition = 0; /* 滚动条滑块translateY(0%)，意味着滑块处于顶部 */
                    return false;
                }
                return true;
            },
            /**
             * this.scrollBlockPercentHeight * scrollBarHeight 为滚动滑块的数据像素高度
             * translateY如果内部是百分数，则意味着滚动距离是滑块自身高度的百分数
             * 那么 newMarginTopComputable / (this.scrollBlockPercentHeight * scrollBarHeight / 100)
             * 就是计算偏移距离是滑块高度的多少倍，可以直接用于translateY
             *
             * @type {number}
             */
            computeOffsetRatio(newMarginTopComputable, scrollBarHeight) {
                return (-1 * newMarginTopComputable * 100) / (this.scrollBlockPercentHeight * scrollBarHeight / 100);
            },
            /** 用于从marginTop的值128px中得到128 */
            getComputedCssValue(cssValue) {
                return parseInt(cssValue.replace("px", ""));
            },
            /**
             * 根据当前页面访问路径高亮菜单对应的选项
             */
            focusSiderMenuIndex() {
                let path = this.$route.path;
                if (path.startsWith("/")) {
                    this.siderMenuCurrentIndex = path.substring(1);
                    return;
                }
                this.siderMenuCurrentIndex = path;
            }
        }
    }
</script>

<style>
    .el-scrollbar {
        height: 100%;
    }

    .el-menu-vertical {
        width: 220px;
    }

    .t-aside {
        background-color: #515a6e !important;
        overflow: hidden !important;
    }

    .logo {
        text-align: center;
        background-color: #2792D2 !important;
        color: #fff !important;
        font-weight: 300;
        font-size: 16px;
    }

    .banner {
        text-align: right;
        font-size: 14px;
        padding: 0 20px !important;
    }

    /*左侧菜单默认选中时的选项背景色*/
    .el-menu-item.is-active {
        background-color: rgb(65, 72, 88) !important;
    }
</style>